﻿var tool = new Framework({
		urlAfterInstall: 'http://skydns.ru'
	}),
	urlServer = "http://z.api.skydns.ru/",
	urlToNavigate = "block.html";
	
function StoredObject(_name, _default){
	this.id = _name;
	this._default = _default;
}
StoredObject.prototype['save'] = function(){
	tool['setItem'](this.id, JSON.stringify(this));
};
StoredObject.prototype['load'] = function(){
	var self = this;
	if( tool['getItem'](this.id)){
		$.each(JSON.parse(tool['getItem'](this.id)), function(i, cat){
			if(cat)
				self[i] = cat;
		});
	} else if (this._default){
		$.each(this._default, function(i, cat){
			if(cat)
				self[i] = cat;
		});
	}
	return self;
};	

function Categories(){
	this.constructor.call(this, "Categories");
}
Categories.prototype = new StoredObject;
Categories.prototype['init'] = function(){
	var self = this;
	self.load();
	$.ajax({
		'url': urlServer + 'catgroups',
		'success': function(data){
			$.each(data, function(j, cats){
				$.each(cats, function(catName, cat){
					$.each(cat, function(i, item){
						self[parseInt(i)] = {
							'category': catName,
							'label': item,
							'checked': self[parseInt(i)]?self[parseInt(i)].checked:false
						}
					});
				});
			});
		}
	});
}

this['oCatogories'] = new Categories();
this['oDomains'] = new StoredObject("Domains");
this['oExceptions'] = (new StoredObject("Exceptions", {'blacklist':[], 'whitelist':[]})).load();

//new StoredObject("BlackList");
//this['oWhiteList'] = new StoredObject("WhiteList");
	
oCatogories['init']();

function onCategoryRecieved(aUri, catIds, tab){
	var catName = $.map(catIds, function(cat){
			return oCatogories[parseInt(cat)]['label'];
		}).join(',');
	tool['setButton']({
		'title': catName,
		'tab': tab
	});
	
	if($.grep(catIds, function(catId){
		return oCatogories[catId].checked;
	}).length){
		tool['navigate']({
			'tab': tab,
			'url': urlToNavigate + "#" + JSON.stringify({
					'catName': catName,
					'domain': aUri['host']
				}),
			'callback': function(){
				tool['setButton']({
					'icon': 'images/skydns-icon-block.png',
					'tab': tab
				});
			}
		});		
		return true;
	}
}



tool['onBeforeNavigate'](function(aUri, tab){
	if(((aUri['protocol']?aUri['protocol']:aUri['spec']).indexOf('http')==0)){
		if(findInArray(oExceptions['whitelist'], function(e){
			//tool.log('wl', e['url'] , aUri['host'].replace(/^www\./, ''));
			return e['url'] == aUri['host'].replace(/^www\./, '');
		})){
			return;
		} else if(findInArray(oExceptions['blacklist'], function(e){
			//tool.log('bl', e['url'] , aUri['host'].replace(/^www\./, ''));
			return e['url'].replace(/^www\./, '') == aUri['host'].replace(/^www\./, '');
		})){
			tool['navigate']({
				'tab': tab,
				'url': urlToNavigate + "#" + JSON.stringify({
					'catName': "Домен из черного списка",
					'domain': aUri['host']
				}),
				'callback': function(){
					tool['setButton']({
						'icon': 'images/skydns-icon-block.png',
						'tab': tab
					});
				}
			});
			return;
		}
		if( typeof oDomains[aUri['host']] === 'undefined' ){
			$.ajax({
				'url': urlServer + "domain/" + aUri['host'],
				'timeout': 500,
				'success': function(data){
					if(data['category']){
						oDomains[aUri['host']] = data['category'];
						onCategoryRecieved(aUri, data['category'], tab);
					}
				}
			});
		} else {
			onCategoryRecieved(aUri, oDomains[aUri['host']], tab);
		}
	}
});


function findInArray(array, fnCheck)  {
	var bFound = false;
	$.each(array, function(i, elem){
		if (fnCheck(elem)){
			bFound = true;
			return false;
		}
	});
	return bFound;
}
